<template>
  <div class="content-wrapper">
    <!-- map -->
    <baidu-map
      class="bm-view"
      :zoom="15"
      id="allmap"
      @click="getLocation"
      @ready="mapReady"
      ak="jUaoSz7mXfWK1MLcZhK70Ii0p8ecqzEB"
    >
      <bm-geolocation
        anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
        :showAddressBar="true"
        :autoLocation="false"
      ></bm-geolocation>
      <div style="display: flex; justify-content: center; margin: 15px">
        <bm-auto-complete
          v-model="searchJingwei"
          :sugStyle="{ zIndex: 999999 }"
        >
        </bm-auto-complete>
        <el-button type="primary" @click="getBaiduMapPoint">搜索</el-button>
      </div>
      <bm-marker
        v-for="(item, index) in locations"
        :key="index"
        :position="{ lng: item.lng, lat: item.lat }"
        :dragging="true"
        animation="BMAP_ANIMATION_BOUNCE"
      >
        <bm-label
          :content="item.name"
          :labelStyle="{ color: 'red', fontSize: '12px' }"
          :offset="{ width: -35, height: 30 }"
        />
      </bm-marker>
      <bm-marker
        v-if="infoWindowShow"
        :position="{ lng: longitude, lat: latitude }"
      >
        <bm-label
          content=""
          :labelStyle="{ color: 'red', fontSize: '24px' }"
          :offset="{ width: -35, height: 30 }"
        />
      </bm-marker>
      <bm-info-window
        :position="{ lng: longitude, lat: latitude }"
        :show="infoWindowShow"
        @close="infoWindowClose"
      >
        <p>纬度:{{ latitude }}</p>
        <p>经度:{{ longitude }}</p>
      </bm-info-window>
      <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
      <!-- 导航工具 -->
      <bm-navigation anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-navigation>
      <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
      <!-- 添加测距工具按钮 -->
      <!--      <div style="position: absolute; top: 10px; right: 10px; z-index: 9999">-->
      <!--        <el-button type="primary" @click="openDistanceTool">测距工具</el-button>-->
      <!--      </div>-->
    </baidu-map>
    <div class="row">
      <div class="col-12 grid-margin stretch-card">
        <div class="card">
          <div class="card-body">
            <form class="form-inline" @submit="research" @submit.native.prevent>
              <label for="inlineFormInputName2">充电站名称：</label>
              <input
                type="text"
                class="form-control mb-2 mr-sm-2"
                v-model="name"
              />
              &nbsp;&nbsp;&nbsp;
              <label for="inlineFormInputGroupUsername2">充电站ID：</label>
              <div class="input-group mb-2 mr-sm-2">
                <input
                  type="number"
                  min="0"
                  class="form-control"
                  v-model="stationId"
                />
              </div>
              &nbsp;&nbsp;&nbsp;
              <div class="input-group mb-2 mr-sm-2">
                <label for="exampleSelectGender">状态：</label>
                <select class="form-control" v-model="status">
                  <option value="-1" selected>全部</option>
                  <option value="0">运行中</option>
                  <option value="1">废弃</option>
                </select>
              </div>
              <button type="submit" class="btn btn-primary mb-2">搜索</button>
              &nbsp;&nbsp;&nbsp;
              <button type="reset" class="btn btn-info mb-2" @click="getAll">
                重置
              </button>
              &nbsp;&nbsp;&nbsp;
              <button
                type="button"
                class="btn btn-danger mb-2"
                data-toggle="modal"
                data-target="#addNewItem"
              >
                新增
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
    <div class="row infoTable">
      <div class="col-md-12 stretch-card">
        <div class="card">
          <div class="card-body">
            <p class="card-title" style="font-size: 30px">充电站信息表</p>
            <div
              class="alert alert-success"
              role="alert"
              v-show="deleteRes === 1"
            >
              删除成功
            </div>
            <div
              class="alert alert-danger"
              role="alert"
              v-show="deleteRes === 2"
            >
              删除失败
            </div>
            <hr />
            <div class="table-responsive">
              <table id="recent-purchases-listing" class="table">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>图片</th>
                    <th>充电站ID</th>
                    <th>充电站名称</th>
                    <th>充电站位置</th>
                    <th>状态</th>
                    <th>价目表</th>
                    <th>收入</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr
                    v-for="(item, index) in data"
                    :key="index"
                    @click="handleRowClick(item.location)"
                  >
                    <td>{{ index + 1 }}</td>
                    <td>
                      <img :src="item.image" style="height:30px weight:auto" />
                    </td>
                    <td>{{ item.id }}</td>
                    <td>{{ item.name }}</td>
                    <td>{{ item.location }}</td>
                    <td v-if="item.status === 0">运行中</td>
                    <td v-else>废弃</td>
                    <td>{{ item.pricelId }}</td>
                    <td>{{ item.revenue }}</td>
                    <td>
                      <button
                        type="button"
                        class="btn btn-primary btn-rounded btn-fw"
                        data-toggle="modal"
                        data-target="#alterItem"
                        @click="alterStation(item.id)"
                      >
                        编辑
                      </button>
                      &nbsp;
                      <button
                        type="button"
                        class="btn btn-danger btn-rounded btn-fw"
                        @click="deleteStation(item.id)"
                      >
                        删除
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <br />
            <div class="col-md-6">
              当前 {{ page }} 页,总 {{ pageSum }} 页,总 {{ number }} 条记录 每页
              <select
                id="pageSize"
                v-model="pageSize"
                aria-controls="DataTables_Table_0"
                size="1"
                name="DataTables_Table_0_length"
              >
                <option value="5">5</option>
                <option value="7">7</option>
                <option value="10">10</option>
              </select>
              条记录
            </div>
            <nav aria-label="Page navigation example">
              <ul class="pagination justify-content-end">
                <li class="page-item">
                  <a class="page-link" v-on:click="changePage(1)">首页</a>
                </li>
                <ul
                  class="pagination justify-content-end"
                  v-for="index in pageSum" v-bind:key="index"
                >
                  <li class="page-item">
                    <a class="page-link" @click="changePage(index)">{{
                      index
                    }}</a>
                  </li>
                </ul>
                <li class="page-item">
                  <a class="page-link" v-on:click="changePage(pageSum)">尾页</a>
                </li>
              </ul>
            </nav>
          </div>
        </div>
      </div>
    </div>
    <div
      class="modal fade"
      id="addNewItem"
      tabindex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">新增充电站信息</h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="alert alert-success" role="alert" v-show="flag === 1">
            添加成功
          </div>
          <div class="alert alert-danger" role="alert" v-show="flag === 2">
            添加失败
          </div>
          <form id="formData" class="form-horizontal">
            <div class="modal-body">
              <div class="form-group">
                <label class="control-label col-lg">充电站经度：</label>
                <div class="col-lg-9">
                  <input
                    type="number"
                    name="iLocationLon"
                    min="0"
                    class="form-control"
                    v-model="iLocationLon"
                  />
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-lg">充电站纬度：</label>
                <div class="col-lg-9">
                  <input
                    type="number"
                    name="iLocationLat"
                    min="0"
                    class="form-control"
                    v-model="iLocationLat"
                  />
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-lg">充电桩名称：</label>
                <div class="col-lg-9">
                  <input
                    type="text"
                    name="name"
                    min="0"
                    class="form-control"
                    v-model="iName"
                  />
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-lg">状态：</label>
                <div class="col-lg-9">
                  <select class="form-control" v-model="iStatus">
                    <option value="0">运行中</option>
                    <option value="1">废弃</option>
                  </select>
                </div>
              </div>
            </div>
          </form>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              取消
            </button>
            <button type="button" class="btn btn-primary" @click="add">
              添加
            </button>
          </div>
        </div>
      </div>
    </div>
    <div
      class="modal fade"
      id="alterItem"
      tabindex="-1"
      aria-labelledby="exampleModalLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">修改充电站信息</h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="alert alert-success" role="alert" v-show="flag === 1">
            修改成功
          </div>
          <div class="alert alert-danger" role="alert" v-show="flag === 2">
            修改失败
          </div>
          <form id="formData" class="form-horizontal">
            <div class="modal-body">
              <div class="form-group">
                <label class="control-label col-lg">充电站经度：</label>
                <div class="col-lg-9">
                  <input
                    type="number"
                    name="iLocationLon"
                    min="0"
                    class="form-control"
                    v-model="oLocationLon"
                  />
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-lg">充电站纬度：</label>
                <div class="col-lg-9">
                  <input
                    type="number"
                    name="iLocationLat"
                    min="0"
                    class="form-control"
                    v-model="oLocationLat"
                  />
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-lg">充电桩名称：</label>
                <div class="col-lg-9">
                  <input
                    type="text"
                    name="name"
                    min="0"
                    class="form-control"
                    v-model="oName"
                  />
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-lg">状态：</label>
                <div class="col-lg-9">
                  <select class="form-control" v-model="oStatus">
                    <option value="0">运行中</option>
                    <option value="1">废弃</option>
                  </select>
                </div>
              </div>
            </div>
          </form>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              data-dismiss="modal"
            >
              取消
            </button>
            <button type="button" class="btn btn-primary" @click="alter">
              修改
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import http from "../axios/http";
import { onMounted, watch, ref } from "vue";
import { BmGeolocation } from "vue-baidu-map-3x";
import { BaiduMap } from "vue-baidu-map-3x";
import { BmScale } from "vue-baidu-map-3x";
import { BmNavigation } from "vue-baidu-map-3x";
import { BmCityList } from "vue-baidu-map-3x";
import { BmMarker } from "vue-baidu-map-3x";
import { BmLabel } from "vue-baidu-map-3x";
import { BmInfoWindow } from "vue-baidu-map-3x";
import { BmAutoComplete } from "vue-baidu-map-3x";
import DistanceTool from "bmaplib.distancetool";
import { onBeforeUnmount } from "vue"; // 导入 ref
const locations = ref([])
// 使用 ref 声明响应式数据
const locations2 = ref([])
const infoWindowShow = ref(false);
const longitude = ref("");
const latitude = ref("");
const searchJingwei = ref("");
const point = ref("");
let mapInstance = null;
let distanceTool = null;

function mapReady({ BMap, map }) {
  point.value = new BMap.Point(118.102, 24.586);
  console.log("kais位置：", point.value);
  map.centerAndZoom(point.value, 16);
  mapInstance = map;
  distanceTool = new DistanceTool(map);
}

const openDistanceTool = () => {
  distanceTool && distanceTool.open();
};

onBeforeUnmount(() => {
  distanceTool && distanceTool.close();
});

function handleRowClick(location) {
  // 处理充电站位置数据，例如打印到控制台
  console.log("充电站位置：", location);
  point.value = new BMap.Point(118.688, 24.873);
  console.log("充电站位置：", point.value);
  // 这里可以根据需要执行其他操作，比如传递位置数据给其他组件或页面
  // 更新地图中心点
  mapInstance.setCenter(point.value);
}

// 定义获取位置的函数
function getLocation(e) {
  longitude.value = e.point.lng; // 使用 value 属性来访问 ref 中的值
  latitude.value = e.point.lat;
  infoWindowShow.value = true;
}

function infoWindowClose() {
  infoWindowShow.value = false;
}

async function getBaiduMapPoint() {
  const myGeo = new BMap.Geocoder();
  //逆地址解析
  myGeo.getPoint(searchJingwei.value, function (point) {
    if (point) {
      latitude.value = point.lat;
      longitude.value = point.lng;
      infoWindowShow.value = true;
      // 更新地图中心点
      mapInstance.setCenter(point);
    }
  });
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

let data = ref();
let number = ref();
let page = ref(1);
let pageSize = ref(5);
let pageSum = ref();

let name = ref("");
let stationId = ref("");
let status = ref("-1");

onMounted(() => {
  getAll();
});

async function getAll() {
  data.value = await http.get(
    "/admin/charge-station?page=1&pageSize=5&stationId=&status=&name="
  );
  status.value = -1;
  name = ref("");
  stationId = ref("");
  number.value = data.value.data.data.total;
  data.value = data.value.data.data.records;
  locations2.value=data.value
  for (const location of data.value) {
    // 如果需要修改位置信息，可以直接操作ref数组
    const [lng, lat] = location.location.split(",")
    locations.value.push({ lng: parseFloat(lng), lat: parseFloat(lat),name:location.name});
    console.log(lng, lat);
  }
  console.log("locations.value")
  console.log(locations.value)
  pageSum.value = parseInt((number.value - 1) / pageSize.value) + 1;
}

watch(pageSize, async (pS) => {
  if (status.value == -1) {
    data.value = await http.get(
      "/admin/charge-station?page=1&pageSize=" +
        pS +
        "&stationId=" +
        stationId.value +
        "&status=&name=" +
        name.value
    );
  } else {
    data.value = await http.get(
      "/admin/charge-station?page=1&pageSize=" +
        pS +
        "&stationId=" +
        stationId.value +
        "&status=" +
        status.value +
        "&name=" +
        name.value
    );
  }
  page.value = 1;
  number.value = data.value.data.data.total;
  data.value = data.value.data.data.records;
  pageSum.value = parseInt((number.value - 1) / pageSize.value) + 1;
});

const changePage = async (pageNum) => {
  if (status.value == -1) {
    data.value = await http.get(
      "/admin/charge-station?page=" +
        pageNum +
        "&pageSize=" +
        pageSize.value +
        "&name=" +
        name.value +
        "&stationId=" +
        stationId.value +
        "&status="
    );
  } else {
    data.value = await http.get(
      "/admin/charge-station?page=" +
        pageNum +
        "&pageSize=" +
        pageSize.value +
        "&name=" +
        name.value +
        "&stationId=" +
        stationId.value +
        "&status=" +
        status.value
    );
  }
  page.value = pageNum;
  number.value = data.value.data.data.total;
  data.value = data.value.data.data.records;
  pageSum.value = parseInt((number.value - 1) / pageSize.value) + 1;
};

const research = async () => {
  if (status.value == -1) {
    data.value = await http.get(
      "/admin/charge-station?page=1&pageSize=" +
        pageSize.value +
        "&name=" +
        name.value +
        "&stationId=" +
        stationId.value +
        "&status="
    );
  } else {
    data.value = await http.get(
      "/admin/charge-station?page=1&pageSize=" +
        pageSize.value +
        "&name=" +
        name.value +
        "&stationId=" +
        stationId.value +
        "&status=" +
        status.value
    );
  }
  page.value = 1;
  number.value = data.value.data.data.total;
  data.value = data.value.data.data.records;
  pageSum.value = parseInt((number.value - 1) / pageSize.value) + 1;
};

let iLocationLon = ref();
let iLocationLat = ref();
let iName = ref();
let iStatus = ref();
let flag = ref();

const add = async () => {
  let params = {
    id: 0,
    image: "",
    location: iLocationLon.value + "," + iLocationLat.value,
    name: iName.value,
    pricelId: 0,
    revenue: 0,
    status: iStatus.value,
  };
  console.log(params);
  let result = await http.post("/admin/charge-station", params);
  if (result.data.code == 1) {
    flag.value = 1;
    sleep(2000);
    location.reload();
  } else {
    flag.value = 2;
  }
};

let deleteRes = ref();

const deleteStation = async (station) => {
  let result = await http.delete("/admin/charge-station/" + station);
  if (result.data.code == 1) {
    deleteRes.value = 1;
    sleep(2000);
    location.reload();
  } else {
    deleteRes.value = 2;
  }
};

let oLocationLon = ref();
let oLocationLat = ref();
let oName = ref();
let oStatus = ref();
let alterId = ref();

const alterStation = async (station) => {
  let result = await http.get("/admin/charge-station/" + station);
  console.log(result);
  oLocationLon.value = result.data.data.location.split(",")[0];
  oLocationLat.value = result.data.data.location.split(",")[1];
  oName.value = result.data.data.name;
  oStatus.value = result.data.data.status;
  alterId.value = station;
};

const alter = async () => {
  let params = {
    id: alterId.value,
    location: oLocationLon.value + "," + oLocationLat.value,
    name: oName.value,
    status: oStatus.value,
  };

  let alterRes = await http.put("/admin/charge-station", params);
  if (alterRes.data.code == 1) {
    flag.value = 1;
    sleep(2000);
    location.reload();
  } else {
    flag.value = 2;
  }
};
</script>

<style scoped>
.bm-view {
  width: 100%;
  height: 40%;
}
.content-wrapper {
  overflow: auto; /* 使用滚动条来显示溢出内容 */
  max-height: 100%; /* 设置最大高度，超出部分会出现滚动条 */
}
</style>
